package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"zhihu/api/internal/types"
	"zhihu/pkg"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		get := r.Header.Get("token")
		handler, b, s := pkg.GetHandler(get)
		if !(b) {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: "服务器繁忙",
				Data:    nil,
			})
			return
		}
		if s != "ok" {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: s,
				Data:    nil,
			})
			return
		}
		r.ParseForm()
		r.Form.Set("userId", handler["user"].(string))
		// Passthrough to next handler if need
		next(w, r)
	}
}
